package com.ys.web.user.friends.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ys.base.BaseConstants;
import com.ys.base.EnumType;
import com.ys.utils.base.http.McodeHandler;
import com.ys.utils.base.j2se.*;
import com.ys.utils.help.GroupUtils;
import com.ys.utils.help.TipUtils;
import com.ys.utils.help.UserUtils;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.GroupKey;
import com.ys.utils.redis.key.UserKey;
import com.ys.utils.redis.key.WalletKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.web.user.friends.mapper.GroupInfoMapper;
import com.ys.web.user.friends.mapper.UserGroupMapper;
import com.ys.web.user.friends.mapper.UserScreenShotsMapper;
import com.ys.web.user.friends.po.BaseGroupInfoPO;
import com.ys.web.user.friends.po.BaseUserScreenShotsPO;
import com.ys.web.user.friends.service.GroupSetService;
import com.ys.web.user.friends.vo.GroupSetVo;
import com.ys.web.user.friends.vo.UserGroupVO;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.ws.bean.MessageResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author quxinjun
 * @version 1.0.0
 * @ClassName GroupSetServiceImpl.java
 * @Description 群组设置实现类
 * @createTime 2021年05月24日 14:01:00
 */
@Slf4j
@Service
public class GroupSetServiceImpl implements GroupSetService {

    @Autowired
    private UserGroupMapper userGroupMapper;

    @Autowired
    private GroupInfoMapper groupInfoMapper;

    @Autowired
    private UserScreenShotsMapper userScreenShotsMapper;

    @Override
    public List<UserGroupVO> getManagerList(Long uid, String groupId, String searchKey, Integer type) {
        List<UserGroupVO> list = userGroupMapper.getManagerList(groupId, type, uid);
        List<UserGroupVO> list1 = new ArrayList<>();
        if (StringHandler.isNotEmpty(searchKey)) {
            for(UserGroupVO obj:list){
                if(obj.getNickName().contains(searchKey) || obj.getRemarkName().contains(searchKey) || obj.getUserGroupRemark().contains(searchKey)) {
                    obj.setUserId(McodeHandler.to32Radix(Long.parseLong(obj.getUserId())));
                    list1.add(obj);
                }
            }
            return list1;

        }
        for(UserGroupVO obj:list){
            obj.setUserId(McodeHandler.to32Radix(Long.parseLong(obj.getUserId())));
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setGroupManager(Long uid, String groupId, String memberId) {
        //验证操作用户是不是群主
        String membersKey = GroupKey.groupMembersKey(groupId);
        GroupUtils.validateIsMaster(uid, groupId);
        String[] split = memberId.split(",");

        List<Long> collect = Arrays.stream(split).map(McodeHandler::from32Radix).collect(Collectors.toList());

        //修改用户身份
        int row = userGroupMapper.setGroupManager(groupId, collect, EnumType.GroupIdentity.MANAGER.getCode());

        if (row > 0) {
            Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<>();
            List<String> nameList = new ArrayList<>();
            collect.forEach(obj -> {
                DefaultTypedTuple<String> defaultTypedTuple = new DefaultTypedTuple<>(String.valueOf(obj), EnumType.GroupIdentity.MANAGER.getCode().doubleValue());
                tuples.add(defaultTypedTuple);
                nameList.add(UserUtils.getCacheUserNickName(groupId, String.valueOf(obj), UserUtils.getCacheUser(obj).getNickName()));
            });
            //修改缓存数据
            Redis.zSet.add(membersKey, tuples);
            //发送推送
            GroupUtils.sendIds(new ArrayList<>(Redis.zSet.range(membersKey, 0, -1)), uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_SET_MANAGER.getCode(),
                    TipUtils.setManager(String.join(",", nameList)));
        } else {
            SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "操作失败");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void undoGroupManager(Long uid, String groupId, String memberId) {
        //验证操作用户是不是群主
        String membersKey = GroupKey.groupMembersKey(groupId);
        GroupUtils.validateIsMaster(uid, groupId);
        String[] split = memberId.split(",");

        List<Long> collect = Arrays.stream(split).map(McodeHandler::from32Radix).collect(Collectors.toList());

        //修改用户身份
        int row = userGroupMapper.setGroupManager(groupId, collect, EnumType.GroupIdentity.MEMBERS.getCode());
        if (row > 0) {

            Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<>();

            List<String> nameList = new ArrayList<>();
            collect.forEach(obj -> {
                DefaultTypedTuple<String> defaultTypedTuple = new DefaultTypedTuple<>(String.valueOf(obj), EnumType.GroupIdentity.MEMBERS.getCode().doubleValue());
                tuples.add(defaultTypedTuple);
                nameList.add(UserUtils.getCacheUserNickName(groupId, String.valueOf(obj), UserUtils.getCacheUser(obj).getNickName()));
            });
            //修改缓存数据
            Redis.zSet.add(membersKey, tuples);
            //发送消息
            GroupUtils.sendIds(new ArrayList<>(Redis.zSet.range(membersKey, 0, -1)), uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_SET_MANAGER.getCode(),
                    TipUtils.setMember(String.join(",", nameList)));
        } else {
            SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "操作失败");
        }
    }

    @Override
    public List<Map<String, Object>> getBannedList() {
        return EnumType.BannedCode.getAll();
    }

    @Override
    public void setBannedUser(Long uid, String groupId, String memberId, Integer code) {
        //验证是不是管理员
        GroupUtils.validateIsManager(uid, groupId);
        //实际禁言到多少秒 （秒）
        long toSeconds = (System.currentTimeMillis() / 1000) + EnumType.BannedCode.getValueByCode(code);
        String key = GroupKey.bannedGroupKey(groupId);
        Map<String, String> cacheMap = new HashMap<>(16);

//        AtomicReference<String> names = new AtomicReference<>("");
        List<String> other = new ArrayList<>();

        Arrays.stream(memberId.split(",")).forEach(o -> {
            long userId = McodeHandler.from32Radix(o);
            cacheMap.put(String.valueOf(userId), String.valueOf(toSeconds));
            other.add(String.valueOf(userId));

//            names.updateAndGet(v -> v + UserUtils.getCacheUserNickName(groupId,
//                    String.valueOf(userId), UserUtils.getCacheUser(userId).getNickName()) + ",");
        });
        Redis.hash.hmset(key, cacheMap);

//        Set<String> members = Redis.zSet.range(GroupKey.groupMembersKey(groupId), 0, -1);
//
//        ThreadUtil.execAsync(() -> {
//            //推送 所有用户
//            GroupUtils.sendIds(members.stream().filter(o -> !other.contains(o)).collect(Collectors.toList()), uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_SET_BANNED.getCode(),
//                    TipUtils.setBannedTip(groupId, String.valueOf(uid), names.get().substring(0, names.get().length() - 1), code));
//        });
        ThreadUtil.execAsync(() -> {
            //推送 指定用户
            GroupUtils.sendIds(other, uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_IS_BANNED.getCode(), "您已被禁止在本群发言");
        });
    }

    @Override
    public void setBanGetRedPacket(Long uid, String groupId, String memberId) {
        //验证是不是管理员
        GroupUtils.validateIsManager(uid, groupId);
//        AtomicReference<String> names = new AtomicReference<>("");
        List<String> other = new ArrayList<>();

        String key = GroupKey.bannedRedPacket(groupId);
        Map<String, String> cacheMap = new HashMap<>(16);

        String date = DateUtil.getDate(new Date(), BaseConstants.BASE_FORMAT);
        Arrays.stream(memberId.split(",")).forEach(o -> {
            long userId = McodeHandler.from32Radix(o);
            cacheMap.put(String.valueOf(userId), date);
            other.add(String.valueOf(userId));

//            names.updateAndGet(v -> v + UserUtils.getCacheUserNickName(groupId,
//                    String.valueOf(userId), UserUtils.getCacheUser(userId).getNickName()) + ",");
        });
        Redis.hash.hmset(key, cacheMap);
//
//        Set<String> members = Redis.zSet.range(GroupKey.groupMembersKey(groupId), 0, -1);
//
//        ThreadUtil.execAsync(() -> {
//            //推送 所有用户
//            GroupUtils.sendIds(members.stream().filter(o -> !other.contains(o)).collect(Collectors.toList()), uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_SET_BAN_GRAD.getCode(),
//                    TipUtils.setBanGradTip(groupId, String.valueOf(uid), names.get().substring(0, names.get().length() - 1)));
//        });

        ThreadUtil.execAsync(() -> {
            //推送 指定用户 您已被禁止在本群抢红包
            GroupUtils.sendIds(other, uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_SET_BAN_GRAD.getCode(), "处理失败");
        });
    }


    @Override
    public List<UserGroupVO> getBannedMembersList(Long uid, String groupId, Integer type, String searchKey) {
        GroupUtils.validateIsManager(uid, groupId);

        Set<String> members = Redis.zSet.rangeByScore(GroupKey.groupMembersKey(groupId),
                EnumType.GroupIdentity.MEMBERS.getCode().doubleValue(),
                EnumType.GroupIdentity.MEMBERS.getCode().doubleValue());

        Map<Object, Object> bannedMembers = Redis.hash.hgetall(GroupKey.bannedGroupKey(groupId));
        long currentSeconds = System.currentTimeMillis() / 1000;
        //拿到了禁言还未过期的人员id
        List<String> bannedList = bannedMembers.entrySet().stream()
                .filter(o -> Long.parseLong(String.valueOf(o.getValue())) > currentSeconds)
                .map(o -> String.valueOf(o.getKey()))
                .collect(Collectors.toList());

        //获取需要的 ids
        List<String> memberList;
        if (type == 1) {
            memberList = bannedList;
        } else {
            memberList = members.stream().filter(o -> !bannedList.contains(o)).collect(Collectors.toList());
        }

        if (StringHandler.isNotEmpty(memberList) && !memberList.isEmpty()) {
            List<UserGroupVO> list = userGroupMapper.findUserGroupBaseInfoList(groupId, memberList, uid);

            if (StringHandler.isNotEmpty(searchKey)) {
                return list.stream()
                        .peek(obj -> obj.setUserId(McodeHandler.to32Radix(Long.parseLong(obj.getUserId()))))
                        .filter(obj -> (obj.getNickName() != null && obj.getNickName().contains(searchKey))
                                || (obj.getRemarkName() != null && obj.getRemarkName().contains(searchKey))
                                || (obj.getUserGroupRemark() != null && obj.getUserGroupRemark().contains(searchKey)))
                        .collect(Collectors.toList());
            }

            return list.stream().peek(obj -> obj.setUserId(McodeHandler.to32Radix(Long.parseLong(obj.getUserId())))).collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }


    @Override
    public List<UserGroupVO> getBanGradMembersList(Long uid, String groupId, Integer type, String searchKey) {
        GroupUtils.validateIsManager(uid, groupId);

        Set<String> members = null;
        Set<String> range = Redis.zSet.range(GroupKey.groupMembersKey(groupId), 0, -1);
        String masterId = range.iterator().next();
        if (masterId.equals(String.valueOf(uid))) {
            members = Redis.zSet.rangeByScore(GroupKey.groupMembersKey(groupId),
                    EnumType.GroupIdentity.MANAGER.getCode().doubleValue(),
                    EnumType.GroupIdentity.MEMBERS.getCode().doubleValue());
        } else {
            members = Redis.zSet.rangeByScore(GroupKey.groupMembersKey(groupId),
                    EnumType.GroupIdentity.MEMBERS.getCode().doubleValue(),
                    EnumType.GroupIdentity.MEMBERS.getCode().doubleValue());
        }


        //拿到了已经被禁止抢红包的成员信息
        Map<Object, Object> banGradMembers = Redis.hash.hgetall(GroupKey.bannedRedPacket(groupId));
        List<String> collect = banGradMembers.entrySet().stream()
                .map(o -> String.valueOf(o.getKey()))
                .collect(Collectors.toList());

        //获取需要的 ids
        List<String> memberList;
        if (type == 1) {
            memberList = collect;
            if (!masterId.equals(String.valueOf(uid))) {
                Set<String> finalMembers = members;
                memberList = collect.stream().filter(finalMembers::contains).collect(Collectors.toList());
            }
        } else {
            memberList = members.stream().filter(o -> !collect.contains(o)).collect(Collectors.toList());
        }

        if (StringHandler.isNotEmpty(memberList) && !memberList.isEmpty()) {
            List<UserGroupVO> list = userGroupMapper.findUserGroupBaseInfoList(groupId, memberList, uid);

            if (StringHandler.isNotEmpty(searchKey)) {
                return list.stream()
                        .peek(obj -> obj.setUserId(McodeHandler.to32Radix(Long.parseLong(obj.getUserId()))))
                        .filter(obj -> (obj.getNickName() != null && obj.getNickName().contains(searchKey))
                                || (obj.getRemarkName() != null && obj.getRemarkName().contains(searchKey))
                                || (obj.getUserGroupRemark() != null && obj.getUserGroupRemark().contains(searchKey)))
                        .collect(Collectors.toList());
            }

            return list.stream().peek(obj -> obj.setUserId(McodeHandler.to32Radix(Long.parseLong(obj.getUserId())))).collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }

    @Override
    public void cancelBanned(Long uid, String groupId, String memberIds) {
        GroupUtils.validateIsManager(uid, groupId);

//        AtomicReference<String> names = new AtomicReference<>("");

        List<String> other = new ArrayList<>();
        Object[] objects = Arrays.stream(memberIds.split(",")).map(o -> {
            String userId = String.valueOf(McodeHandler.from32Radix(o));
//            names.updateAndGet(v -> v + UserUtils.getCacheUserNickName(groupId,
//                    userId, UserUtils.getCacheUser(userId).getNickName()) + ",");
            other.add(userId);
            return userId;
        }).toArray();

        //删除对应hash field
        Redis.hash.delHash(GroupKey.bannedGroupKey(groupId), objects);

//        Set<String> members = Redis.zSet.range(GroupKey.groupMembersKey(groupId), 0, -1);
//        ThreadUtil.execAsync(() -> {
//            //推送
//            GroupUtils.sendIds(members.stream().filter(o -> !other.contains(o)).collect(Collectors.toList()), uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_SET_BANNED.getCode(),
//                    TipUtils.cancelBannedTip(groupId, String.valueOf(uid), names.get().substring(0, names.get().length() - 1)));
//        });
        ThreadUtil.execAsync(() -> {
            //推送
            GroupUtils.sendIds(other, uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_IS_NON_BANNED.getCode(), "您已被允许在本群发言");
        });

    }

    @Override
    public void cancelBanGetRedPacket(Long uid, String groupId, String memberId) {
        GroupUtils.validateIsManager(uid, groupId);
//        AtomicReference<String> names = new AtomicReference<>("");
        List<String> other = new ArrayList<>();
        Object[] objects = Arrays.stream(memberId.split(",")).map(o -> {
            String userId = String.valueOf(McodeHandler.from32Radix(o));
//            names.updateAndGet(v -> v + UserUtils.getCacheUserNickName(groupId,
//                    userId, UserUtils.getCacheUser(userId).getNickName()) + ",");
            other.add(userId);
            return userId;
        }).toArray();
        //删除对应hash field
        Redis.hash.delHash(GroupKey.bannedRedPacket(groupId), objects);
//        Set<String> members = Redis.zSet.range(GroupKey.groupMembersKey(groupId), 0, -1);
//        ThreadUtil.execAsync(() -> {
//            //推送
//            GroupUtils.sendIds(members.stream().filter(o -> !other.contains(o)).collect(Collectors.toList()), uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_SET_BAN_GRAD.getCode(),
//                    TipUtils.cancelBanGradTip(groupId, String.valueOf(uid), names.get().substring(0, names.get().length() - 1)));
//        });
        ThreadUtil.execAsync(() -> {
            //推送
            GroupUtils.sendIds(other, uid, groupId, EnumType.MessageCode.MESSAGE_GROUP_SET_BAN_GRAD.getCode(), "您已被允许在本群抢红包");
        });

    }

    @Override
    public GroupSetVo getCurrentGroupSetForUser(Long uid, String groupId) {
        GroupSetVo groupSetVo = new GroupSetVo();
        String gkey = GroupKey.groupInfoKey(groupId);
        String jsonStr = Redis.str.get(gkey);
        BaseGroupInfoPO baseGroupInfoPO = null;
        if (StringHandler.isNotEmpty(jsonStr)) {
            baseGroupInfoPO = JsonUtil.jsonToBean(jsonStr, BaseGroupInfoPO.class);
        } else {
            baseGroupInfoPO = groupInfoMapper.selectByPrimaryKey(groupId);

            //添加群信息至缓存
            // TODO 缓存没更新，去过没收到推送 ，全员禁止领红包不生效
            Redis.str.set(gkey, JsonUtil.toJson(baseGroupInfoPO));
            Redis.key.setKeyTimeout(gkey, BaseConstants.SAVE_TIME);
        }
        //设置当前组是否是全员禁言
        groupSetVo.setGroupStatus(baseGroupInfoPO.getStatus() != null && baseGroupInfoPO.getStatus());
        groupSetVo.setIsBanned(baseGroupInfoPO.getIsBanned() != null && baseGroupInfoPO.getIsBanned());
        groupSetVo.setIsMemberProtect(baseGroupInfoPO.getIsMemberProtect() != null && baseGroupInfoPO.getIsMemberProtect());
        groupSetVo.setIsScreenNotice(baseGroupInfoPO.getIsScreenNotice() != null && baseGroupInfoPO.getIsScreenNotice());
        groupSetVo.setIsAdvertIntercept(baseGroupInfoPO.getIsAdvertIntercept() != null && baseGroupInfoPO.getIsAdvertIntercept());
        groupSetVo.setIsGrad(true);
        groupSetVo.setGradCount(baseGroupInfoPO.getGradCount() == null ? 0 : baseGroupInfoPO.getGradCount());
        groupSetVo.setGradTime(baseGroupInfoPO.getGradTime() == null ? 0 : baseGroupInfoPO.getGradTime());
        groupSetVo.setIsFreeze(baseGroupInfoPO.getIsFreeze() != null ? baseGroupInfoPO.getIsFreeze() : false);
        //判断是否可以抢红包
        String key2 = GroupKey.bannedRedPacket(groupId);
        if (Redis.key.exists(key2)) {
            Object o = Redis.hash.hGet(key2, String.valueOf(uid));
            if (StringHandler.isNotEmpty(o)) {
                groupSetVo.setIsGrad(false);
            }
        }

        //设置成员身份
        groupSetVo.setUserIdentity(null);
        String key3 = GroupKey.groupMembersKey(groupId);
        if (Redis.key.exists(key3)) {
            Double rank = Redis.zSet.score(key3, String.valueOf(uid));
            if (StringHandler.isNotEmpty(rank)) {
                groupSetVo.setUserIdentity(rank.intValue());
            }
        }

        if (groupSetVo.getUserIdentity() < EnumType.GroupIdentity.MEMBERS.getCode()) {
            groupSetVo.setIsGrad(true);
        } else {
            if (baseGroupInfoPO.getIsGradAll() != null) {
                groupSetVo.setIsGrad(!baseGroupInfoPO.getIsGradAll() && groupSetVo.getIsGrad());
            }
        }

        //设置还剩多少秒
        String timeStr = null;
        String key1 = GroupKey.bannedGroupKey(groupId);
        if (Redis.key.exists(key1)) {
            timeStr = (String) Redis.hash.hGet(key1, String.valueOf(uid));
        }
        long time = 0L;
        if (timeStr != null) {
            //如果设置的时间大于当前时间  证明还在禁言中null
            if (Long.parseLong(timeStr) < (System.currentTimeMillis() / 1000)) {
                if (Redis.hash.hasValue(GroupKey.bannedGroupKey(groupId), String.valueOf(uid))) {
                    Redis.hash.delHash(GroupKey.bannedGroupKey(groupId), String.valueOf(uid));
                }
            } else {
                time = Long.parseLong(timeStr);
            }
        }
        groupSetVo.setBannedTime(time);
        return groupSetVo;
    }

    @Override
    public List<?> getGroupMessageClearSetList() {
        return EnumType.MessageClearCode.getAll();
    }

    @Override
    public void screensHotsNotice(Long uid, String groupId, String url) {
        Set<String> members = Redis.zSet.range(GroupKey.groupMembersKey(groupId), 0, -1);
        String masterId = members.iterator().next();
        //群主截图不管
        if (String.valueOf(uid).equals(masterId)) {
            return;
        }
        LoginInfo cacheUser = UserUtils.getCacheUser(uid);
        String name = cacheUser.getNickName();
        String groupName = (String) Redis.hash.hGet(GroupKey.groupUserGroupRemarkKey(groupId), String.valueOf(uid));
        //如果群组备注存在  返回群组备注  不然返回用户昵称
        name = StringHandler.isNotEmpty(groupName) ? groupName : name;
        String currentTime = DateHandler.getDate(new Date(), BaseConstants.BASE_FORMAT);

        //插入数据
        BaseUserScreenShotsPO baseUserScreenShotsPO = new BaseUserScreenShotsPO();
        baseUserScreenShotsPO.setUrl(url);
        baseUserScreenShotsPO.setUserId(String.valueOf(uid));
        baseUserScreenShotsPO.setNickName(cacheUser.getNickName());
        baseUserScreenShotsPO.setGroupId(groupId);
        baseUserScreenShotsPO.setGroupRemark(groupName);
        baseUserScreenShotsPO.setCreateTime(currentTime);
        userScreenShotsMapper.insertSelective(baseUserScreenShotsPO);


        BaseGroupInfoPO cacheGroupInfo = GroupUtils.getCacheGroupInfo(groupId);
        MessageResponseBean messageResponseBean = new MessageResponseBean();

        messageResponseBean.setUserName(name);
        messageResponseBean.setFrom(McodeHandler.to32Radix(uid));
        messageResponseBean.setGroupId(groupId);
        messageResponseBean.setWindowId(BaseConstants.GROUP_PREFIX + groupId);
        messageResponseBean.setAvatarUrl(cacheUser.getAvatarUrl());
        messageResponseBean.setMessageId(IdUtil.simpleUUID());
//        messageResponseBean.setGroupName(cacheGroupInfo.getName() + "(" + members.size() + ")");
        messageResponseBean.setGroupName(cacheGroupInfo.getName());
        messageResponseBean.setGroupPic(cacheGroupInfo.getPic());
        messageResponseBean.setCode(EnumType.MessageCode.MESSAGE_LAUNCH_SCREEN_HOST_NOTICE.getCode());
        messageResponseBean.setData(TipUtils.screensHotsTip(name, currentTime));
        GroupUtils.sendIfAbsent(messageResponseBean, masterId, messageResponseBean.getWindowId());
    }

    @Override
    public List<BaseUserScreenShotsPO> getCurrentGroupScreenList(Long uid, String groupId) {
        GroupUtils.validateIsMaster(uid, groupId);
        List<BaseUserScreenShotsPO> list = userScreenShotsMapper.selectList(groupId);
        if (!list.isEmpty()) {
            return list.stream().peek(x -> x.setUserId(McodeHandler.to32Radix(Long.parseLong(x.getUserId())))).collect(Collectors.toList());
        }
        return list;
    }

    @Override
    public void clearMessageRightAway(Long uid, String groupId) {
        GroupUtils.validateIsManager(uid, groupId);
        Set<String> members = Redis.zSet.range(GroupKey.groupMembersKey(groupId), 0, -1);
        Date date = new Date();
        MessageResponseBean messageResponseBean = new MessageResponseBean();
        messageResponseBean.setCode(EnumType.MessageCode.MESSAGE_CLEAR.getCode());
        messageResponseBean.setCreateTime(DateUtil.getDate(date, BaseConstants.BASE_FORMAT));
        messageResponseBean.setGroupId(groupId);
        messageResponseBean.setWindowId(BaseConstants.GROUP_PREFIX + groupId);

        members.forEach(x -> {
            ThreadUtil.execAsync(() -> {
                //修改已读最大消息id
                //查找当前群最大的消息id
//                int suffix = Integer.parseInt(groupId) % BaseConstants.gChatTableNum;
//                Long maxMessageId = gChatMapper.findMaxMessageId(suffix, Long.parseLong(groupId), DateUtil.getDate(date, BaseConstants.BASE_FORMAT));
//
//                GChatReadPO gChatReadPO = gChatReadMapper.selectObject(Long.parseLong(groupId), Long.parseLong(x));
//                if (StringHandler.isEmpty(gChatReadPO)) {
//                    gChatReadPO = new GChatReadPO();
//                    gChatReadPO.setFrom(groupId)
//                            .setTo(x)
//                            .setMaxId(maxMessageId);
//                    gChatReadMapper.insertSelective(gChatReadPO);
//                } else {
//                    gChatReadPO.setMaxId(maxMessageId);
//                    gChatReadMapper.updateByPrimaryKeySelective(gChatReadPO);
//                }

                //通知类型消息处理
                String key = UserKey.noticeKey(x);
                List<String> messageJsonList = Redis.list.range(key, 0L, -1L);
                if (StringHandler.isNotEmpty(messageJsonList)) {
                    //取到之后删除数据
                    Redis.key.del(key);
//                    List<String> messageList = new ArrayList<>();
//                    messageJsonList.stream().forEach(o -> {
//                        MessageResponseBean message = JsonUtil.jsonToBean(o, MessageResponseBean.class);
//                        if (StringHandler.isNotEmpty(message) &&
//                                (message.getWindowId().startsWith(BaseConstants.SINGLE_PREFIX) || DateUtil.getDate(date, BaseConstants.BASE_FORMAT).compareTo(message.getCreateTime()) < 0)) {
//                            messageList.add(JsonUtil.toJson(message));
//                        }
//                    });

                    List<String> collect = messageJsonList.stream().map(o -> JsonUtil.jsonToBean(o, MessageResponseBean.class))
                            .filter(o -> o.getWindowId().startsWith(BaseConstants.SINGLE_PREFIX) ||
                                    (o.getWindowId().startsWith(BaseConstants.GROUP_PREFIX) && o.getGroupId().equals(groupId) && DateUtil.getDate(date, BaseConstants.BASE_FORMAT).compareTo(o.getCreateTime()) < 0))
                            .map(JsonUtil::toJson)
                            .collect(Collectors.toList());


                    if (!collect.isEmpty()) {
                        Redis.list.pushList(key, collect);
                    }
                }
            });
        });
        ThreadUtil.execAsync(() -> members.forEach(o -> GroupUtils.sendIfAbsentForClear(messageResponseBean, o)));
    }

    @Override
    public void setGradTimeForGroup(Long uid, String groupId, Integer count, Integer time) {
        //验证是不是管理员或者群主
        GroupUtils.validateIsManager(uid, groupId);
        BaseGroupInfoPO baseGroupInfoPO = GroupUtils.getCacheGroupInfo(groupId);

        baseGroupInfoPO.setGradTime(time * 60);
        baseGroupInfoPO.setGradCount(count);
        groupInfoMapper.updateByPrimaryKeySelective(baseGroupInfoPO);
        Redis.str.set(GroupKey.groupInfoKey(groupId), JsonUtil.toJson(baseGroupInfoPO));
        Set<String> members = Redis.zSet.rangeByScore(GroupKey.groupMembersKey(groupId), EnumType.GroupIdentity.MEMBERS.getCode().doubleValue(), EnumType.GroupIdentity.MEMBERS.getCode().doubleValue());

        ThreadUtil.execAsync(() -> {
            MessageResponseBean messageResponseBean = new MessageResponseBean();

            messageResponseBean.setCode(EnumType.MessageCode.MESSAGE_GROUP_SET_GRAD_TIME_COUNT.getCode());
            messageResponseBean.setGroupId(groupId);
            messageResponseBean.setWindowId(BaseConstants.GROUP_PREFIX + groupId);
            messageResponseBean.setData(JsonUtil.toJson(MapHandler.initMap("count", StringHandler.getString(count), "time", StringHandler.getString(time))));
            members.forEach(x -> {
                GroupUtils.sendIfAbsent(messageResponseBean, x, messageResponseBean.getWindowId());
            });
        });
        ThreadUtil.execAsync(() -> {
            //如果由限制改为不限制，清空原有redis数据
            if (count == 0 || time == 0) {
                String riskKey = WalletKey.gradGroupKey(groupId);
                Set<String> keys = Redis.key.keys(riskKey);
                keys.forEach(x -> Redis.key.del(x));
            }
        });
    }

}
